package org.atlantis.grosbeak.lang;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 包含多个异常的一个集合异常类。
 * 
 * @author <a href="mailto:seenoevil.cn@gmail.com">SeeNoEvil</a>
 * 
 */
@SuppressWarnings("serial")
public class UniteException extends Exception {

	private List<Throwable> list;

	public UniteException() {
		list = new ArrayList<Throwable>();
	}

	public UniteException add(Throwable e) {
		list.add(e);
		return this;
	}

	@Override
	public Throwable getCause() {
		if (list.isEmpty())
			return null;
		return list.get(0);
	}

	@Override
	public String getLocalizedMessage() {
		StringBuilder sb = new StringBuilder();
		for (Throwable e : list)
			sb.append(e.getLocalizedMessage()).append('\n');
		return sb.toString();
	}

	@Override
	public String getMessage() {
		StringBuilder sb = new StringBuilder();
		for (Throwable e : list)
			sb.append(e.getMessage()).append('\n');
		return sb.toString();
	}

	@Override
	public StackTraceElement[] getStackTrace() {
		List<StackTraceElement> stes = new LinkedList<StackTraceElement>();
		for (Throwable e : list)
			for (StackTraceElement ste : e.getStackTrace())
				stes.add(ste);
		return stes.toArray(new StackTraceElement[stes.size()]);
	}

	@Override
	public void printStackTrace() {
		for (Throwable e : list) {
			e.printStackTrace();
			System.err.println();
		}
	}

	@Override
	public void printStackTrace(PrintStream ps) {
		for (Throwable e : list)
			e.printStackTrace(ps);
	}

	@Override
	public void printStackTrace(PrintWriter pw) {
		for (Throwable e : list)
			e.printStackTrace(pw);
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (Throwable e : list)
			sb.append(e.toString()).append('\n');
		return sb.toString();
	}
}
